package system;

import java.io.*;
import java.util.*;

import system.back.Fetcher;
import system.back.Loader;
import system.back.Parser;
import system.back.Ranker;
import system.struct.ParserResult;
import system.struct.SearchEntry;
import system.util.Util;

public class MySystem {

	static Loader loader;
	static Parser parser;
	static Fetcher fetcher;
	static Ranker ranker;
	
	public static void main(String[] args) {
		Util.time();
		initial();
		query();
	}
	
	static void initial() {
		loader = new Loader();
		parser = new Parser(loader);
		fetcher = new Fetcher(loader);
		ranker = new Ranker();
		loader.loadAll();
	}
	
	static void query() {
		try{
			String line = "";
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			while (!line.equals("exit")) {
				System.out.print("$ query: ");
				line = br.readLine().toLowerCase().trim();
				if (line.substring(0, 2).equals("-c")) {
					testConcept(line.substring(3));
					continue;
				}
				Util.time();
				ParserResult pr = parser.parse(line);
				ArrayList<SearchEntry> seList = fetcher.fetchLog(pr);
				SearchEntry[] result = ranker.rank(pr, seList);
				showResult(result);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	static void testConcept(String concept) {
		System.out.println(loader.hasCnpt(concept));
	}
	
	static void showResult(SearchEntry[] list) {
		for (int i = 0; i < list.length; i++) {
			if (i == 0 || list[i].qIndex() != list[i - 1].qIndex()) 
				System.out.println(list[i].info());
		}
		System.out.print("query finished: ");
		Util.time();
	}

}
